package core

import (
	"fmt"
	"io/ioutil"
	"os"
	"plugin"
	"strings"
)

const FilePath = "config/plugin"

// 业务组件化封装，按照转换逻辑封装不同组件
var supplierPlugin = make(map[string]SupplierPlugin, 10)

type RequestMethod string

const (
	GET  RequestMethod = "GET"
	POST RequestMethod = "POST"
)

func GetSupplierPlugin(name string) SupplierPlugin {
	return supplierPlugin[name]
}

type SupplierPlugin struct {
	plugin *plugin.Plugin
}

func (s *SupplierPlugin) GetPlugin() *plugin.Plugin {
	return s.plugin
}

// 初始化 init 程序 封装加载plugin插件，然后批量加载此插件
func Init() {
	fileList, err := getAllFile(getFilePath())

	if err != nil {
		panic(err)
	}
	fmt.Println("加载fileList: ", fileList, " filePath: ", getFilePath())
	for i := range fileList {
		p, err := plugin.Open(fileList[i])
		if err != nil {
			fmt.Println("出现错误: ", err.Error())
		} else {
			filePath := strings.Split(fileList[i], "/")
			supplierPlugin[filePath[len(filePath)-1]] = SupplierPlugin{
				plugin: p,
			}
		}
	}
	fmt.Println("加载之后的数据为: ", supplierPlugin)
}
func getFilePath() string {
	dir, err := os.Getwd()
	if err != nil {
		dir = "./"
	}
	return dir + "/" + FilePath
}

func getAllFile(pathname string) (s []string, err error) {
	rd, err := ioutil.ReadDir(pathname)
	if err != nil {
		fmt.Print("出现错误: ", err.Error())
		return s, err
	}

	for _, fi := range rd {
		if !fi.IsDir() && strings.Contains(fi.Name(), ".so") {
			fullName := pathname + "/" + fi.Name()
			s = append(s, fullName)
		}
	}
	return s, nil
}
